#include "animetask.h"

AnimeTask::AnimeTask()
{
    this->fiche = QString();
    this->parsing_anime = 0;
    this->parsing_anime_infos = 0;
    this->parsing_episodes = 0;
    this->parsing_bonus = 0;
}

AnimeTask::AnimeTask(QNetworkProxy const& proxy, const QString &fiche, const QString &url_image, QRegularExpression *expression, QRegularExpression *infos, QRegularExpression *episodes, QRegularExpression *bonus){
    this->fiche = fiche;
    this->url_image = url_image;
    this->parsing_anime = expression;
    this->parsing_anime_infos = infos;
    this->parsing_episodes = episodes;
    this->parsing_bonus = bonus;
    this->proxy = proxy;
}

void AnimeTask::run(){
    QFile data(QString("data/fiches/")+this->fiche.left(fiche.length()-5)+QString(".xml"));
    if(!data.exists()){
        QUrl qurl = QUrl(QString("http://www.otaku-attitude.net/")+fiche);
        QNetworkAccessManager *manager = new QNetworkAccessManager;
        manager->setProxy(this->proxy);
        QNetworkRequest request(qurl);
        QNetworkReply *reponse = manager->get(request);
        QEventLoop loop;
        QObject::connect(reponse,SIGNAL(finished()),&loop,SLOT(quit()));
        loop.exec();

        string html = reponse->readAll().data();
        delete reponse;

        QRegularExpressionMatchIterator match = this->parsing_anime->globalMatch(QString(html.c_str()));
        //while(match.hasNext()){

        if(!match.hasNext()) {
            qDebug() << "No match for regex..." << endl;
        } else {
            QDomDocument doc;
            QDomElement root = doc.createElement("fiche");


            QDomElement titre = doc.createElement("titre");
            QDomElement description = doc.createElement("description");
            QDomElement genres = doc.createElement("genres");
            QDomElement diffusion = doc.createElement("diffusion");
            QDomElement createur = doc.createElement("createur");
            QDomElement disponibles = doc.createElement("disponibles");
            QDomElement totaux = doc.createElement("totaux");
            QDomElement team = doc.createElement("team");
            QDomElement serveur = doc.createElement("serveur");

            QRegularExpressionMatch resultat = match.next();
            description.appendChild(doc.createCDATASection(resultat.captured(1)));

            match = this->parsing_anime_infos->globalMatch(QString(html.c_str()));

            while(match.hasNext()) {
                QRegularExpressionMatch resultat = match.next();

                diffusion.appendChild(doc.createTextNode(resultat.captured(2)));
                createur.appendChild(doc.createCDATASection(resultat.captured(3)));
                disponibles.appendChild(doc.createCDATASection(resultat.captured(4)));
                totaux.appendChild(doc.createCDATASection(resultat.captured(5)));
                team.appendChild(doc.createCDATASection(resultat.captured(6)));
                serveur.appendChild(doc.createTextNode(resultat.captured(7)));
            }

            QDomElement episodes = doc.createElement("episodes");
            match = this->parsing_episodes->globalMatch(QString(html.c_str()));
            while(match.hasNext()) {
                QRegularExpressionMatch resultat = match.next();

                QDomElement episode = doc.createElement("episode");
                QDomElement id = doc.createElement("id");
                QDomElement num = doc.createElement("num");
                QDomElement codec = doc.createElement("codec");
                QDomElement resolution = doc.createElement("resolution");
                QDomElement duree = doc.createElement("duree");
                QDomElement taille = doc.createElement("taille");
                QDomElement dateajout = doc.createElement("dateajout");
                QDomElement hits = doc.createElement("hits");

                id.appendChild(doc.createTextNode(resultat.captured(1)));
                num.appendChild(doc.createTextNode(resultat.captured(2)));
                codec.appendChild(doc.createTextNode(resultat.captured(3)));
                resolution.appendChild(doc.createTextNode(resultat.captured(4)));
                duree.appendChild(doc.createTextNode(resultat.captured(5)));
                taille.appendChild(doc.createTextNode(resultat.captured(6)));
                dateajout.appendChild(doc.createTextNode(resultat.captured(7)));
                hits.appendChild(doc.createTextNode(resultat.captured(8)));

                episode.appendChild(id);
                episode.appendChild(num);
                episode.appendChild(codec);
                episode.appendChild(resolution);
                episode.appendChild(duree);
                episode.appendChild(taille);
                episode.appendChild(dateajout);
                episode.appendChild(hits);
                episodes.appendChild(episode);
            }

            QDomElement bonus = doc.createElement("bonus");
            match = this->parsing_bonus->globalMatch(QString(html.c_str()));
            while(match.hasNext()) {
                QRegularExpressionMatch resultat = match.next();

                QDomElement fichier = doc.createElement("fichier");
                QDomElement id = doc.createElement("id");
                QDomElement nom = doc.createElement("nom");
                QDomElement taille = doc.createElement("taille");
                QDomElement dateajout = doc.createElement("dateajout");
                QDomElement hits = doc.createElement("hits");

                id.appendChild(doc.createTextNode(resultat.captured(1)));
                nom.appendChild(doc.createCDATASection(resultat.captured(2)));
                taille.appendChild(doc.createTextNode(resultat.captured(3)));
                dateajout.appendChild(doc.createTextNode(resultat.captured(4)));
                hits.appendChild(doc.createTextNode(resultat.captured(5)));

                fichier.appendChild(id);
                fichier.appendChild(nom);
                fichier.appendChild(taille);
                fichier.appendChild(dateajout);
                fichier.appendChild(hits);
                bonus.appendChild(fichier);
            }

            root.appendChild(description);
            root.appendChild(diffusion);
            root.appendChild(createur);
            root.appendChild(disponibles);
            root.appendChild(totaux);
            root.appendChild(team);
            root.appendChild(serveur);
            root.appendChild(episodes);
            root.appendChild(bonus);
            doc.appendChild(root);


            if (data.open(QFile::WriteOnly | QFile::Truncate)) {
                QTextStream out(&data);
                doc.save(out, 4);

                /*emit afficherTexteLauncher(QString("Écriture du fichier xml..."));

                std::ostringstream transformers;
                message = "";
                transformers << nb_anime_total;
                message += transformers.str();
                message += " animes";

                emit afficherTexteLauncher(QString(message.c_str()));*/

                data.close();
            } else {
                //emit afficherTexteLauncher(QString("Impossible d'écrire le fichier xml..."));
                qDebug() << "Erreur ecriture fiche xml" << endl;
            }

            QUrl url = QUrl(this->url_image);
            QFileInfo fileInfo(url.path());
            QString fileName= QString("data/img/")+fileInfo.fileName();

            if (QFile::exists(fileName)) {
            /*QMessageBox::information(this, tr("HTTP"),
            tr("There already exists a file called %1 in "
            "the current directory.")
            .arg(fileName));*/
            }

            QFile file(fileName);
            if (!file.open(QIODevice::WriteOnly)) {
            /*QMessageBox::information(this, tr("HTTP"),
            tr("Unable to save the file %1: %2.")
            .arg(fileName).arg(file->errorString()));*/
            }

            //file.setFileName(fileName);
            //file.open(QIODevice::WriteOnly);

            QNetworkRequest request(url);
            QNetworkReply *reponse = manager->get(request);
            QEventLoop loop;
            QObject::connect(reponse,SIGNAL(finished()),&loop,SLOT(quit()));
            loop.exec();

            file.write(reponse->readAll());
            file.close();
            delete reponse;
            reponse = 0;
        }

        delete manager;
    }
}
